package WinterHomework.day12;

//Leetcode58 最后一个单词的长度
public class Demo01 {
    public static void main(String[] args) {
        String s = "Hello World";
        System.out.println(lengthOfLastWord(s));
    }

    public static int lengthOfLastWord(String s) {
        //数组区分
//        String[] str = s.split(" ");
//        int n = str.length-1;
//        char[] ch = str[n].toCharArray();
//        return ch.length;
        //倒序查找
//        int n = s.length() - 1;
//        while (s.charAt(n) == ' ') {
//            n--;
//        }
//        int wordLength = 0;
//        while (n >= 0 && s.charAt(n) != ' ') {
//            wordLength++;
//            n--;
//        }
//        return wordLength;
        //答案
        if (s.isEmpty()) {
            return 0;
        }
        int len = s.length() - 1;
        int wordLength = 0;
        for (int i = len; i >= 0; i--) {
            if (s.charAt(i) != ' ') {
                wordLength++;
                if (i != 0 && s.charAt(i - 1) == ' ') {
                    break;
                }
            }
        }
        return wordLength;
    }
}
